#include "dbhelper.h"
#include "db.h"
#include "qqclient.hpp"
#include "qun.hpp"
#include "debug.hpp"
dbhelper helper;
extern std::vector<qqqun*> g_QunUpdates;
extern InfoRecords gAllInfoRecords;
extern QunMemberRecords gQunMemberRecords;
extern qqclient* qq;
dbhelper::dbhelper()
{
    //connect(this,SIGNAL(terminated()),this,SLOT(OnTerminate()));
    this->start();
}
dbhelper::~dbhelper()
{
    if(this->isRunning())
    {
        this->terminate();
    }
}

void dbhelper::OnTerminate()
{
    DBG("OnTerminate");
}

void dbhelper::run()
{
    while(this->isRunning())
    {
		
        //群好友信息
        if(this->isFinished())
            break;
        if(gQunMemberRecords.size()>0)
        {
            db &infoDB = db::GetInstance();
            infoDB.open(qq->number);
            //infoDB.lockMemory();
            infoDB.BeginTrans();
            while(gQunMemberRecords.size()>0)
            {

                STR_qunmember &qm = gQunMemberRecords.front();
                infoDB.writeQunMember(qm.qid, qm.m->number,qm.m->nickname);
                gQunMemberRecords.erase(gQunMemberRecords.begin());
            }

            infoDB.Commit();
            //infoDB.unlockMemeory();
        }

        //聊天信息
        if(gAllInfoRecords.size()>0 )
        {
            db &infoDB = db::GetInstance();
            infoDB.open(qq->number);
			QMutexLocker ql(&infoDB.mutex_chat);
            //infoDB.lockMemory();
            infoDB.BeginTrans();
            while(gAllInfoRecords.size()>0 )
            {
                STR_inforecord &record = gAllInfoRecords.front();
                infoDB.writeRecord(record.type, record.fromid, record.toid , record.toqunid , record.time, record.info );
                gAllInfoRecords.erase(gAllInfoRecords.begin());
            }
            infoDB.Commit();
            //infoDB.unlockMemeory();
        }
        if(g_QunUpdates.size()>0)
        {
            //db &infoDB = db::GetInstance();
            //infoDB.lockMemory();
            while(g_QunUpdates.size()>0)
            {

                qqqun* q = g_QunUpdates.front();
                DBG("qun_update_memberinfo(%s)",q->name);
                qun_update_memberinfo( qq, q);
                g_QunUpdates.erase(g_QunUpdates.begin());
            }


            //infoDB.unlockMemeory();
        }
        else
        this->sleep(5);
    }
}
